﻿using System;
using System.Linq;
using System.Text;

namespace SomeKit.Authentication
{
    /// <summary>
    /// Helper class that enables encoding and decoding of username/password pairs for Basic Authentication.
    /// </summary>
    public static class BasicAuthenticationHelper
    {
        /// <summary>
        /// Encodes the username/password pair for basic authentication
        /// </summary>
        /// <param name="userName">The user name.</param>
        /// <param name="password">The password.</param>
        /// <returns>Base 64 encoded string of the total token.</returns>
        public static string Encode(string userName, string password)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + password));
        }
        /// <summary>
        /// Fetches the username and the password from the encoded credentials.
        /// </summary>
        /// <param name="credentials">Base 64 encoded credentials.</param>
        /// <param name="userName">The user name</param>
        /// <param name="password">The password</param>
        public static void Decode(string credentials, out string userName, out string password)
        {
            byte[] userNamePwdBytes;
            try
            {
                userNamePwdBytes = Convert.FromBase64String(credentials);
            }
            catch { throw new ArgumentNullException("Authorization", "Missing information"); }
            var userNamePwd = new string(userNamePwdBytes.Select(b => (char)b).ToArray());
            var userNamePwdPair = userNamePwd.Split(':');
            if (userNamePwdPair.Length != 2)
                throw new ArgumentNullException("Authorization", "Missing information");
            userName = userNamePwdPair[0];
            password = userNamePwdPair[1];
        }
    }
}
